package com.sky.controller.user;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserAuthorizationDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户相关接口
 */
@RestController
@RequestMapping("/user/user")
@Api(tags = "用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    /**
     * 用户微信登录接口，该接口可以自动注册新用户，并且返回一个用户对应的token
     * 笔记：将具体登录业务：即查找旧用户，保存新用户交给服务层来做，将生成token，包装Result的对应VO交给控制层来做。此处分层思路很重要
     * @param userLoginDTO 包含临时授权码的DTO
     * @return 包含用户微信openid（唯一标识符）和token
     */
    @PostMapping("/login")
    @ApiOperation("用户微信登录接口")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) throws JsonProcessingException {
        log.info("用户登录：{}",userLoginDTO);
        //服务层登录功能：向微信服务器请求openid，查找老用户，保存新用户，并且返回用户对应的User对象
        User user=userService.login(userLoginDTO);

        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());//用id来生成token
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        log.info("用户的token值为：{}",token);
        //封装vo对象返回
        UserLoginVO userLoginVO=new UserLoginVO();
        BeanUtils.copyProperties(user,userLoginVO);
        userLoginVO.setToken(token);
        return Result.success(userLoginVO);
    }
}
